using System;
using System.Reflection;

namespace Weever.Json.Serialization.v1
{
    class ReflectedMemberInfo
    {
        private MemberInfo _memberInfo;
        private Type _memberType;
        private string _jsonName;

        protected ReflectedMemberInfo()
        {}

        public MemberInfo MemberInfo
        {
            get { return _memberInfo; }
        }

        public Type MemberType
        {
            get { return _memberType; }
        }

        public string JsonName
        {
            get { return _jsonName; }
        }

        public static ReflectedMemberInfo CreateFromMemberInfo(MemberInfo mi)
        {
            ReflectedMemberInfo rmi = new ReflectedMemberInfo();
            rmi._memberInfo = mi;
            object[] nameAttributes = mi.GetCustomAttributes(typeof (JsonNameAttribute), true);
            object[] camelNameAttributes = mi.GetCustomAttributes(typeof(CamelCaseAttribute), true);

            if (nameAttributes.Length > 0)
                rmi._jsonName = ((JsonNameAttribute)nameAttributes[0]).Name;
            else if (camelNameAttributes.Length > 0)
                rmi._jsonName = char.ToLower(mi.Name[0]) + mi.Name.Substring(1);
            else
                rmi._jsonName = mi.Name;

            if (mi.MemberType == MemberTypes.Field)
                rmi._memberType = ((FieldInfo) mi).FieldType;
            else if (mi.MemberType == MemberTypes.Property)
                rmi._memberType = ((PropertyInfo) mi).PropertyType;
            else
                throw new InvalidOperationException("unsupported MemberInfo.MemberType");

            return rmi;
        }

        public override string ToString()
        {
            return _memberInfo.ToString();
        }
    }
}
